from django.shortcuts import render
from django.urls import reverse

from df_user.models import Passport, Address
from django.shortcuts import redirect
from django.http import JsonResponse
from django.views.decorators.http import require_POST, require_GET, require_http_methods
from df_order.models import OrderBasic
from django.core.paginator import Paginator

# /user/register/
from utils.decorators import login_required


@require_http_methods(['GET', 'POST'])
def register(request):
    '''显示注册页面'''
    if request.method == 'GET':
        return render(request, 'df_user/register.html')
    else:
        # 获取数据
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')

        # 保存数据
        Passport.objects.add_one_passport(username=username, password=password, email=email)

        # todo（hans): 发送邮件
        return redirect('/user/login/')


# /user/register_handle
@require_POST
def register_handle(request):
    '''用户信息注册'''
    # 1、接受用户注册信息
    username = request.POST.get('user_name')
    password = request.POST.get('pwd')
    email = request.POST.get('email')

    # 2、保存用户信息进数据库

    # passport = Passport()
    # passport.username = username
    # passport.password = password
    # passport.email = email
    # passport.save()

    Passport.objects.add_one_passport(username=username, password=password, email=email)

    # 3、重定向到登录界面
    return redirect('/user/login/')


# /user/check_user_exist/
@require_GET
def check_user_exist(request):
    '''校验用户是否存在'''
    # 1、获取用户名
    username = request.GET.get('username')
    # 2、根据用户名，检查用户是否存在
    passport = Passport.objects.get_one_passport(username=username)

    # 3、查到， 返回json {'res':0}  查不到，返回json {'res':1}
    if passport:
        # 用户名已存在
        return JsonResponse({'res':0})
    else:
        # 用户名可用
        return JsonResponse({'res':1})


# /user/login/
def login(request):
    # 用户登录界面
    # 判断cookies中是否有 username
    if 'username' in request.COOKIES:
        username = request.COOKIES['username']
    else:
        username = ''

    return render(request, 'df_user/login.html', {'username':username})


#/user/login_check/
def login_check(request):
    # 用户登录校验
    # 获取用户名和密码
    username = request.POST.get('username')
    password = request.POST.get('password')

    # 根据用户名和密码，查找用户
    passport = Passport.objects.get_one_passport(username=username, password=password)

    # 如果用户存在
    if passport:
        # 获取上次访问位置（中间件中存储到session中）
        if request.session.has_key('pre_url_path'):
            next = request.session['pre_url_path']
        else:
            next = '/' # 默认跳转到首页

        jres = JsonResponse({'res': 1, 'next': next})

        remember = request.POST.get('remember')
        if remember == True:
            jres.set_cookie('username', username, max_age=14*24*3600)

        # 记录登录状态、用户名、用户id
        request.session['islogin'] = True
        request.session['username'] = username
        request.session['passport_id'] = passport.id

        return jres
    else:
        return JsonResponse({'res': 0})


def logout(request):
    # 用户退出登录
    # 清除用户登录信息
    request.session.flush()
    # 跳转到首页
    return redirect('/')


@login_required
def user(request):
    passport_id = request.session.get('passport_id')
    addr = Address.objects.get_one_address(passport_id=passport_id)

    # todo :获取用户的历史浏览记录 获取5条
    return render(request, 'df_user/user_center_info.html', {'addr': addr, 'page': 'user'})


@login_required
@require_http_methods(['GET', 'POST'])
def address(request):
    passport_id = request.session.get('passport_id')

    if request.method == 'GET':
        addr = Address.objects.get_one_address(passport_id=passport_id)
        return render(request, 'df_user/user_center_site.html', {'addr': addr, 'page': 'addr'})
    elif request.method == 'POST':
        username = request.POST.get('username')
        addr = request.POST.get('addr')
        zip_code =request.POST.get('zip_code')
        phone = request.POST.get('phone')

        Address.objects.add_one_address(passport_id=passport_id,
                                        recipient_name=username,
                                        recipient_addr=addr,
                                        recipient_phone=phone,
                                        zip_code=zip_code,
                                        )
        # return redirect('/user/address/')
        return redirect(reverse('address'))


# /user/order/
# 显示用户中心，订单页
@login_required
def order(request, pindex):
    # 获取用户id

    passport_id = request.session.get('passport_id')

    # 获取基本订单信息列表
    order_basic_list = OrderBasic.objects.get_order_basic_list_info_by_passport(passport_id=passport_id)

    # 进行分页  5个一页
    paginator = Paginator(order_basic_list,5)

    print(pindex)

    # 获取要显示的是第几页
    if pindex == '':
        pindex = 1
    else:
        pindex = int(pindex)

    # 获取要显示的页面的订单信息列表
    order_basic_list = paginator.page(pindex)

    # 分页后的总页数
    nums_page = paginator.num_pages

    # 小于5页，全部显示
    if nums_page < 5:
        pages = range(1, nums_page+1)
    elif pindex <=3:        # 当前页小于3，显示前5页
        pages = range(1, 6)
    elif nums_page-pindex <=2:  # 最后3页， 显示最后5页
        pages = range(pindex-2, nums_page+1)
    else:       # 中间页，显示当前页和前面两页、后边两页
        pages = range(pindex-2, pindex+3)

    return render(request, 'df_user/user_center_order.html',
                  {'page': 'order', 'order_basic_list':order_basic_list, 'pages': pages})
